<?php
require_once 'includes/header.php';
require_once 'includes/DatabaseHelper.php';

require_once 'includes/functions.php';

// 初始化数据库连接
$db = Database::getInstance();

// 检查是否有用户ID
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    $_SESSION['flash_message'] = '无效的用户ID';
    $_SESSION['flash_type'] = 'danger';
    header('Location: users.php');
    exit;
}

$userId = (int)$_GET['id'];

// 获取用户信息
$user = $db->fetchRow("SELECT * FROM " . DB_PREFIX . "users WHERE id = ?", [$userId]);

if (!$user) {
    $_SESSION['flash_message'] = '用户不存在';
    $_SESSION['flash_type'] = 'danger';
    header('Location: users.php');
    exit;
}

// 分页
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 15;
$offset = ($page - 1) * $perPage;

// 筛选条件
$game_id = isset($_GET['game_id']) ? (int)$_GET['game_id'] : 0;
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';

// 构建WHERE条件
$whereConditions = ["ua.user_id = ?"];
$whereParams = [$userId];

if ($game_id > 0) {
    $whereConditions[] = "ua.game_id = ?";
    $whereParams[] = $game_id;
}

if (!empty($date_from)) {
    $whereConditions[] = "ua.unlocked_at >= ?";
    $whereParams[] = $date_from . ' 00:00:00';
}

if (!empty($date_to)) {
    $whereConditions[] = "ua.unlocked_at <= ?";
    $whereParams[] = $date_to . ' 23:59:59';
}

$whereClause = implode(' AND ', $whereConditions);

// 排序
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'date';
$order = isset($_GET['order']) ? $_GET['order'] : 'desc';

$orderClause = "";
switch ($sort) {
    case 'name':
        $orderClause = "a.name " . ($order == 'asc' ? 'ASC' : 'DESC');
        break;
    case 'points':
        $orderClause = "a.points " . ($order == 'asc' ? 'ASC' : 'DESC');
        break;
    case 'game':
        $orderClause = "g.name " . ($order == 'asc' ? 'ASC' : 'DESC');
        break;
    case 'date':
    default:
        $orderClause = "ua.unlocked_at " . ($order == 'asc' ? 'ASC' : 'DESC');
        break;
}

// 获取记录总数
$totalAchievements = $db->fetchColumn("
    SELECT COUNT(*) 
    FROM " . DB_PREFIX . "user_achievements ua
    WHERE $whereClause
", $whereParams);

// 获取用户成就
$achievements = $db->fetchAll("
    SELECT ua.*, a.name as achievement_name, a.description, a.icon, a.points, g.name as game_name
    FROM " . DB_PREFIX . "user_achievements ua
    JOIN " . DB_PREFIX . "achievements a ON ua.achievement_id = a.id
    LEFT JOIN " . DB_PREFIX . "games g ON ua.game_id = g.id
    WHERE $whereClause
    ORDER BY $orderClause
    LIMIT ?, ?
", array_merge($whereParams, [$offset, $perPage]));

// 获取所有游戏（用于筛选）
$games = $db->fetchAll("
    SELECT g.id, g.name 
    FROM " . DB_PREFIX . "games g
    JOIN " . DB_PREFIX . "user_achievements ua ON g.id = ua.game_id
    WHERE ua.user_id = ?
    GROUP BY g.id
    ORDER BY g.name ASC
", [$userId]);

// 计算总页数
$totalPages = ceil($totalAchievements / $perPage);

// 统计数据
$totalPoints = $db->fetchColumn("
    SELECT SUM(a.points) 
    FROM " . DB_PREFIX . "user_achievements ua
    JOIN " . DB_PREFIX . "achievements a ON ua.achievement_id = a.id
    WHERE ua.user_id = ?
", [$userId]);
$totalPoints = $totalPoints ?: 0;

$lastUnlocked = $db->fetchRow("
    SELECT a.name, ua.unlocked_at
    FROM " . DB_PREFIX . "user_achievements ua
    JOIN " . DB_PREFIX . "achievements a ON ua.achievement_id = a.id
    WHERE ua.user_id = ?
    ORDER BY ua.unlocked_at DESC
    LIMIT 1
", [$userId]);

$totalPossibleAchievements = $db->fetchColumn("SELECT COUNT(*) FROM " . DB_PREFIX . "achievements");
$completionPercentage = ($totalAchievements > 0 && $totalPossibleAchievements > 0) 
    ? round(($totalAchievements / $totalPossibleAchievements) * 100, 1) 
    : 0;

// 准备分页URL
$paginationUrl = "user_achievements.php?id=$userId";
if ($game_id > 0) $paginationUrl .= "&game_id=$game_id";
if (!empty($date_from)) $paginationUrl .= "&date_from=$date_from";
if (!empty($date_to)) $paginationUrl .= "&date_to=$date_to";
if ($sort != 'date') $paginationUrl .= "&sort=$sort";
if ($order != 'desc') $paginationUrl .= "&order=$order";
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1><i class="bi bi-trophy"></i> 用户成就</h1>
    <div>
        <a href="user_detail.php?id=<?php echo $userId; ?>" class="btn btn-outline-secondary me-2">
            <i class="bi bi-arrow-left"></i> 返回用户详情
        </a>
        <a href="users.php" class="btn btn-outline-secondary">
            <i class="bi bi-people"></i> 用户列表
        </a>
    </div>
</div>

<div class="alert alert-info">
    <strong><?php echo htmlspecialchars($user['username']); ?></strong> 的成就 - 共 <?php echo $totalAchievements; ?> 项成就
</div>

<!-- 统计卡片 -->
<div class="row mb-4">
    <div class="col-md-4">
        <div class="card bg-primary text-white h-100">
            <div class="card-body">
                <h5 class="card-title"><i class="bi bi-star"></i> 总积分</h5>
                <h3><?php echo number_format($totalPoints); ?> 分</h3>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <div class="card bg-success text-white h-100">
            <div class="card-body">
                <h5 class="card-title"><i class="bi bi-award"></i> 成就完成率</h5>
                <h3>
                    <?php echo $completionPercentage; ?>%
                    <small>(<?php echo $totalAchievements; ?>/<?php echo $totalPossibleAchievements; ?>)</small>
                </h3>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <div class="card bg-info text-white h-100">
            <div class="card-body">
                <h5 class="card-title"><i class="bi bi-clock-history"></i> 最近解锁</h5>
                <h3>
                    <?php if ($lastUnlocked): ?>
                        <?php echo date('Y-m-d', strtotime($lastUnlocked['unlocked_at'])); ?>
                        <small>(<?php echo htmlspecialchars($lastUnlocked['name']); ?>)</small>
                    <?php else: ?>
                        暂无成就
                    <?php endif; ?>
                </h3>
            </div>
        </div>
    </div>
</div>

<!-- 筛选表单 -->
<div class="card mb-4">
    <div class="card-header">
        <i class="bi bi-funnel"></i> 筛选条件
    </div>
    <div class="card-body">
        <form action="user_achievements.php" method="get" class="row g-3">
            <input type="hidden" name="id" value="<?php echo $userId; ?>">
            
            <div class="col-md-3">
                <label for="game_id" class="form-label">游戏</label>
                <select name="game_id" id="game_id" class="form-select">
                    <option value="0">所有游戏</option>
                    <?php foreach ($games as $game): ?>
                        <option value="<?php echo $game['id']; ?>" <?php if ($game_id == $game['id']) echo 'selected'; ?>>
                            <?php echo htmlspecialchars($game['name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="col-md-3">
                <label for="date_from" class="form-label">开始日期</label>
                <input type="date" class="form-control" id="date_from" name="date_from" value="<?php echo $date_from; ?>">
            </div>
            
            <div class="col-md-3">
                <label for="date_to" class="form-label">结束日期</label>
                <input type="date" class="form-control" id="date_to" name="date_to" value="<?php echo $date_to; ?>">
            </div>
            
            <div class="col-md-3 d-flex align-items-end">
                <div class="btn-group w-100">
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-search"></i> 筛选
                    </button>
                    <a href="user_achievements.php?id=<?php echo $userId; ?>" class="btn btn-outline-secondary">
                        <i class="bi bi-x-circle"></i> 重置
                    </a>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- 成就列表 -->
<div class="card mb-4">
    <div class="card-header">
        <i class="bi bi-list-check"></i> 成就列表
    </div>
    <div class="card-body">
        <?php if (!empty($achievements)): ?>
            <div class="table-responsive">
                <table class="table table-hover table-striped">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>图标</th>
                            <th>
                                <a href="<?php echo buildSortUrl('name', $sort, $order, $paginationUrl); ?>" class="text-decoration-none">
                                    成就名称
                                    <?php echo getSortIcon('name', $sort, $order); ?>
                                </a>
                            </th>
                            <th>描述</th>
                            <th>
                                <a href="<?php echo buildSortUrl('game', $sort, $order, $paginationUrl); ?>" class="text-decoration-none">
                                    相关游戏
                                    <?php echo getSortIcon('game', $sort, $order); ?>
                                </a>
                            </th>
                            <th>
                                <a href="<?php echo buildSortUrl('points', $sort, $order, $paginationUrl); ?>" class="text-decoration-none">
                                    积分
                                    <?php echo getSortIcon('points', $sort, $order); ?>
                                </a>
                            </th>
                            <th>
                                <a href="<?php echo buildSortUrl('date', $sort, $order, $paginationUrl); ?>" class="text-decoration-none">
                                    解锁时间
                                    <?php echo getSortIcon('date', $sort, $order); ?>
                                </a>
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $count = $offset + 1; ?>
                        <?php foreach ($achievements as $achievement): ?>
                            <tr>
                                <td><?php echo $count++; ?></td>
                                <td class="text-center">
                                    <?php if (!empty($achievement['icon'])): ?>
                                        <img src="<?php echo htmlspecialchars($achievement['icon']); ?>" alt="成就图标" class="img-thumbnail" width="40" height="40">
                                    <?php else: ?>
                                        <div class="bg-light rounded d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                            <i class="bi bi-trophy text-warning"></i>
                                        </div>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo htmlspecialchars($achievement['achievement_name']); ?></td>
                                <td><?php echo htmlspecialchars($achievement['description']); ?></td>
                                <td>
                                    <?php if (!empty($achievement['game_name'])): ?>
                                        <?php echo htmlspecialchars($achievement['game_name']); ?>
                                    <?php else: ?>
                                        <span class="text-muted">全局成就</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge bg-warning text-dark">
                                        <?php echo $achievement['points']; ?> 分
                                    </span>
                                </td>
                                <td><?php echo date('Y-m-d H:i', strtotime($achievement['unlocked_at'])); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            
            <!-- 分页 -->
            <?php if ($totalPages > 1): ?>
                <nav>
                    <ul class="pagination justify-content-center">
                        <li class="page-item <?php if ($page <= 1) echo 'disabled'; ?>">
                            <a class="page-link" href="<?php if ($page <= 1) echo '#'; else echo $paginationUrl . '&page=' . ($page - 1); ?>">上一页</a>
                        </li>
                        
                        <?php
                        $startPage = max(1, $page - 2);
                        $endPage = min($totalPages, $page + 2);
                        
                        if ($startPage > 1) {
                            echo '<li class="page-item"><a class="page-link" href="' . $paginationUrl . '&page=1">1</a></li>';
                            if ($startPage > 2) {
                                echo '<li class="page-item disabled"><a class="page-link" href="#">...</a></li>';
                            }
                        }
                        
                        for ($i = $startPage; $i <= $endPage; $i++) {
                            echo '<li class="page-item ' . ($page == $i ? 'active' : '') . '">
                                <a class="page-link" href="' . $paginationUrl . '&page=' . $i . '">' . $i . '</a>
                            </li>';
                        }
                        
                        if ($endPage < $totalPages) {
                            if ($endPage < $totalPages - 1) {
                                echo '<li class="page-item disabled"><a class="page-link" href="#">...</a></li>';
                            }
                            echo '<li class="page-item"><a class="page-link" href="' . $paginationUrl . '&page=' . $totalPages . '">' . $totalPages . '</a></li>';
                        }
                        ?>
                        
                        <li class="page-item <?php if ($page >= $totalPages) echo 'disabled'; ?>">
                            <a class="page-link" href="<?php if ($page >= $totalPages) echo '#'; else echo $paginationUrl . '&page=' . ($page + 1); ?>">下一页</a>
                        </li>
                    </ul>
                </nav>
            <?php endif; ?>
        <?php else: ?>
            <div class="alert alert-info">
                没有找到符合条件的成就记录。
            </div>
        <?php endif; ?>
    </div>
</div>

<?php
// 排序链接构建函数
function buildSortUrl($column, $currentSort, $currentOrder, $baseUrl) {
    $newOrder = ($currentSort === $column && $currentOrder === 'desc') ? 'asc' : 'desc';
    return $baseUrl . "&sort=" . $column . "&order=" . $newOrder;
}

// 排序图标函数
function getSortIcon($column, $currentSort, $currentOrder) {
    if ($currentSort !== $column) {
        return '<i class="bi bi-arrow-down-up text-muted"></i>';
    } else {
        return ($currentOrder === 'desc') 
            ? '<i class="bi bi-sort-down"></i>' 
            : '<i class="bi bi-sort-up"></i>';
    }
}
?>

<?php require_once 'includes/footer.php'; ?> 